<template>
	<page-meta :page-style="'overflow:' + (popupVisible ? 'hidden' : 'visible')"></page-meta>
	<view class="page-container bg-grey">
		<up-navbar placeholder :auto-back="true" title="提交订单"></up-navbar>

		<view class="card-wrap">
			<view class="card trip-info">
				<view class="display-name-wrap">
					<view class="display-name">{{ packageInfo.spu_display_name }}</view>
					<view class="box">
						<view class="box-item">
							<image :src="`${imgBaseUrl}rili-icon.png`" class="icon" />
							<text class="middle">使用日期：</text>
							<text class="right">{{ formatDate(date) }}出发</text>
						</view>
						<view class="box-item">
							<image :src="`${imgBaseUrl}trip-package-icon.png`" class="icon" />
							<text class="middle">预订套餐：</text>
							<text class="right">{{ packageInfo.display_name }}</text>
						</view>
					</view>
				</view>

				<view class="section">
					<view class="tips" v-if="packageInfo.tourist_refund_title">
						<image :src="`${imgBaseUrl}tourist-info-icon.png`" class="tourist-info-icon" />
						<text>{{ packageInfo.tourist_refund_title }}</text>
					</view>
					<view class="order-notice">
						<OrderNotice
							:display_name="packageInfo.spu_display_name"
							:use_rule="packageInfo.use_rule"
							:sale_tips="packageInfo.sale_tips"
							:booking_tips="packageInfo.booking_tips"
						/>
					</view>
				</view>

				<view class="ops">
					<AmountOperation
						ref="amountOperationRef"
						:unit_price="price_in_cent"
						@total-price-change="handleTotalPriceChange"
					/>
				</view>
			</view>

			<TouristInfo ref="touristInfoRef" :tourist_contact_rule="packageInfo.tourist_contact_rule" />
			<ContactInfo ref="contactInfoRef" :tourist_contact_rule="packageInfo.tourist_contact_rule" />
		</view>

		<view class="bottom">
			<view class="price">
				<text class="prefix font-oppo">¥</text>
				<text class="num font-oppo">
					{{ hasPrices ? priceInCent(total_price) : "--" }}
				</text>
			</view>
			<view class="btn" :class="{ disabled: !hasPrices }" @click="handleSubmit">
				{{ hasPrices ? "立即预定" : "暂不可预定" }}
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from "vue"
import { onLoad } from "@dcloudio/uni-app"
import XEUtils from "xe-utils"
import dayjs from "dayjs"
import { $getTripSales, $getTripListPrice, $createTrip } from "@/api/trip"
import { priceInCent } from "@/mixins/mixins"
import OrderNotice from "../components/order-notice.vue"
import AmountOperation from "../components/amount-operation.vue"
import TouristInfo from "../components/tourist-info.vue"
import ContactInfo from "../components/contact-info.vue"
const imgBaseUrl = inject("imgBaseUrl")

const date = ref("")
const id = ref("")
const skuId = ref("")
const popupVisible = ref(false)
const packageInfo = ref({})
const amountOperationRef = ref(null)
const total_price = ref(0)
const touristInfoRef = ref(null)
const contactInfoRef = ref(null)
const price_in_cent = ref("")

const hasPrices = computed(() => price_in_cent.value !== "")

const handleTotalPriceChange = (price) => (total_price.value = price)
const handlePopupVisible = (visible) => {
	popupVisible.value = visible
}

const formatDate = (date) => {
	const arr = date.split("-")

	return arr.reduce((pre, cur, index) => {
		const suffix = { 0: "年", 1: "月", 2: "日" }[index]

		return pre + cur + suffix
	}, "")
}

const handleSubmit = XEUtils.debounce(async () => {
	console.log("btn clicked")
	if (!hasPrices.value) return

	if (!touristInfoRef.value.touristList) {
		uni.showToast({ title: "请填写游客信息", icon: "none" })
		return
	} else {
		const diff = touristInfoRef.value.touristList.length - touristInfoRef.value.touristList.filter(Boolean).length

		if (diff > 0) {
			uni.showToast({ title: "请填写游客信息", icon: "none" })
			return
		}
	}

	if (!contactInfoRef.value.contactInfo) {
		uni.showToast({ title: "请填写联系信息", icon: "none" })
		return
	}

	const {
		contact_require_id_value,
		contact_require_mobile,
		contact_require_name,

		tourist_require_id_value,
		tourist_require_mobile,
		tourist_require_name,
	} = packageInfo.value.tourist_contact_rule
	const contactInfo = contactInfoRef.value.contactInfo

	const params = {
		sku_id: skuId.value,
		tour_date: date.value,
		price_in_cent: price_in_cent.value,
		quantity: amountOperationRef.value.amount,
		tourists: touristInfoRef.value.touristList.map((item) => ({
			...(tourist_require_name ? { name: item.name } : {}),
			...(tourist_require_mobile ? { mobile: item.mobile } : {}),
			...(tourist_require_id_value ? { id_type: item.id_type, id_number: item.id_value } : {}),
		})),
	}

	if (contact_require_id_value) {
		// params.contact_id_type = contactInfo.id_type
		params.contact_id_type = 10
		params.contact_id_number = contactInfo.id_value
	}

	if (contact_require_name) {
		params.contact_name = contactInfo.name
	}

	if (contact_require_mobile) {
		params.contact_mobile = contactInfo.mobile
	}

	const data = await $createTrip({ data: JSON.stringify(params) })

	uni.navigateTo({ url: `/pages/order/pay?stmt_id=${data.id}` })
}, 500)

const getTripDetail = async () => {
	const data = await $getTripSales(skuId.value)

	packageInfo.value = data

	// 从 prices 中找是否存在 date 这天
	const res = packageInfo.value.prices.find((item) => item.date === date.value)

	if (res) {
		price_in_cent.value = res.price_in_cent
	} else {
		const data = await $getTripListPrice(
			skuId.value,
			packageInfo.value.latest_sale_date,
			dayjs(packageInfo.value.latest_sale_date).add(90, "day").format("YYYY-MM-DD")
		)

		const list = data.list

		const result = list.find((item) => item.date === date.value)

		if (result) {
			price_in_cent.value = result.price_in_cent
		}
	}
}

onLoad((options) => {
	id.value = options.id
	skuId.value = options.sku_id
	date.value = options.date

	getTripDetail()
})

onMounted(() => {
	uni.$on("submit-order-popup-visible", handlePopupVisible)
})

onUnmounted(() => {
	uni.$off("submit-order-popup-visible", handlePopupVisible)
})
</script>

<style lang="scss" scoped>
@import "../ticket/index.scss";

.page-container {
	padding-bottom: calc(128rpx + 48rpx + env(safe-area-inset-bottom));
}

.card-wrap {
	margin: 24rpx;
}

.trip-info {
	padding-top: 24rpx;

	.display-name-wrap {
		padding-bottom: 32rpx;
		border-bottom: 1rpx solid #f3f3f3;

		.display-name {
			font-weight: 600;
			font-size: 36rpx;
			color: rgba(0, 0, 0, 0.9);
			line-height: 50rpx;
		}

		.box {
			margin-top: 24rpx;
			padding: 20rpx 16rpx;
			background: #f7f8fa;
			border-radius: 16rpx;

			&-item {
				display: flex;
				align-items: flex-start;

				&:not(:last-child) {
					margin-bottom: 16rpx;
				}

				.icon {
					flex-shrink: 0;
					width: 28rpx;
					height: 28rpx;
					margin-top: 4rpx;
				}

				.middle {
					margin-left: 12rpx;
					font-size: 24rpx;
					line-height: 36rpx;
					color: #86909c;
				}

				.right {
					flex: 1;
					word-break: break-all;
					font-size: 24rpx;
					line-height: 36rpx;
					color: #4e5969;
				}
			}
		}
	}

	.section {
		margin-top: 32rpx;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;

		.tips {
			display: flex;
			align-items: flex-start;
			margin-right: 50rpx;
			font-size: 24rpx;
			color: #bc8400;
			line-height: 34rpx;

			.tourist-info-icon {
				flex-shrink: 0;
				width: 28rpx;
				height: 28rpx;
				margin-top: 4rpx;
				margin-right: 8rpx;
			}
		}

		.order-notice {
			flex-shrink: 0;
		}
	}

	.ops {
		margin-top: 32rpx;
	}
}

.bottom {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100vw;
	height: calc(128rpx + env(safe-area-inset-bottom));
	height: calc(128rpx + constant(safe-area-inset-bottom));
	padding: 24rpx 24rpx calc(24rpx + env(safe-area-inset-bottom));
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	z-index: 10;
	box-shadow: inset 0rpx 2rpx 0rpx 0rpx #f1f2f5;

	.price {
		display: flex;
		align-items: baseline;
		color: #fe4f2f;

		.prefix {
			font-size: 28rpx;
			line-height: 36rpx;
		}

		.num {
			font-size: 48rpx;
			line-height: 36rpx;
		}
	}

	.btn {
		width: 320rpx;
		height: 80rpx;
		line-height: 80rpx;
		background: #fee038;
		border-radius: 40rpx;
		font-weight: 600;
		font-size: 28rpx;
		color: #1d2129;
		text-align: center;

		&.disabled {
			background-color: #f6f6f9;
		}
	}
}
</style>
